package common.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.model.response.base.Result;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 使用response输出JSON
 *
 * @author 米泽鹏
 * @since 2021-07-31 5:06 下午
 */
@Slf4j
public class ResponseUtil {

	private ResponseUtil() {
		throw new AssertionError("不可实例化");
	}

	/**
	 * 使用response输出JSON
	 */
	public static void out(HttpServletResponse servletResponse, Result<?> result) {
		PrintWriter out = null;
		try {
			out = servletResponse.getWriter();
			out.println(JSON.toJSONString(result, Constants.SERIALIZER_FEATURES));
		} catch (Exception e) {
			log.error("输出JSON出错", e);
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}

	/**
	 * 响应内容
	 */
	public static void getResponse(HttpServletResponse httpServletResponse, String msg, Integer status) {
		try (PrintWriter writer = httpServletResponse.getWriter()) {
			writer.print(JSONObject.toJSONString(new Result<>(status, msg, null, null), Constants.SERIALIZER_FEATURES));
		} catch (IOException e) {
			log.error(ExceptionUtil.getRootCauseMessage(e), e);
		}
	}

	public static void handleResponse(HttpServletResponse response, int status) {
		handleResponse(response, status, StandardCharsets.UTF_8.name(), Constants.HEADER_CONTENT_TYPE);
	}

	public static void handleResponse(HttpServletResponse response, int status, String charset, String contentType) {
		response.setStatus(status);
		response.setCharacterEncoding(charset);
		response.setContentType(contentType);
	}

}
